package com.company.huisuo.utils

import android.content.Context
import android.graphics.Bitmap
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur

/**
 * 模糊效果工具类
 */
object BlurUtil {

    /**
     * 对Bitmap进行高斯模糊处理
     * @param context 上下文
     * @param bitmap 原始图片
     * @param radius 模糊半径(1-25)，越大越模糊
     * @return 模糊后的Bitmap
     */
    fun blur(context: Context, bitmap: Bitmap, radius: Float = 25f): Bitmap? {
        var rs: RenderScript? = null
        try {
            val output = Bitmap.createBitmap(
                bitmap.width,
                bitmap.height,
                Bitmap.Config.ARGB_8888
            )

            rs = RenderScript.create(context)
            val blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs))
            val tmpIn = Allocation.createFromBitmap(rs, bitmap)
            val tmpOut = Allocation.createFromBitmap(rs, output)

            blurScript.setRadius(radius.coerceIn(1f, 25f))
            blurScript.setInput(tmpIn)
            blurScript.forEach(tmpOut)
            tmpOut.copyTo(output)

            return output
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        } finally {
            rs?.destroy()
        }
    }
}
